<?php 
//encrypt($pwd);
//decrypt($pwd);

function encrypt($value)
{
	$key="waC3Vpx9Xv0rcFyYoZej0H0GqrrtLwsE";
	$cipher="AES-256-CBC";
	
	$iv = openssl_random_pseudo_bytes(16);

	$value = openssl_encrypt(serialize($value), $cipher, $key, 0, $iv);

	if ($value === false) {
		echo 'Could not encrypt the data.';
	}

	$mac = hash_hmac('sha256',$iv = base64_encode($iv), $value);

	return base64_encode(json_encode(compact('iv', 'value', 'mac')));
}

function decrypt($payload)
{
	$key="waC3Vpx9Xv0rcFyYoZej0H0GqrrtLwsE";
	$cipher="AES-256-CBC";
	
	$payload = getJsonPayload($payload);

	$iv = base64_decode($payload['iv']);

	$decrypted = openssl_decrypt($payload['value'], $cipher, $key, 0, $iv);

	if ($decrypted === false) {
		//echo 'Could not decrypt the data.';
	}

	return unserialize($decrypted);
}

/**
 * 加密函数
 * @param   string  $str    加密前的字符串
 * @param   string  $key    密钥
 * @return  string  加密后的字符串
 */
function encrypt2($str, $key = AUTH_KEY)
{
	$coded = '';
	$keylength = strlen($key);

	for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength)
	{
		$coded .= substr($str, $i, $keylength) ^ $key;
	}

	return str_replace('=', '', base64_encode($coded));
}

/**
 * 解密函数
 * @param   string  $str    加密后的字符串
 * @param   string  $key    密钥
 * @return  string  加密前的字符串
 */
function decrypt2($str, $key = AUTH_KEY)
{
	$coded = '';
	$keylength = strlen($key);
	$str = base64_decode($str);

	for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength)
	{
		$coded .= substr($str, $i, $keylength) ^ $key;
	}

	return $coded;
}


function getJsonPayload($payload)
{
	$payload = json_decode(base64_decode($payload), true);

	if (!$payload || invalidPayload($payload)) {
		//echo 'The payload is invalid.';
	}

	return $payload;
}

function invalidPayload($data)
{
	return !is_array($data) || !isset($data['iv']) || !isset($data['value']) || !isset($data['mac']);
}
?>